<template>
  <div>
    <van-nav-bar
      title="欢迎登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-form validate-first @failed="onFailed">
      <!-- 通过 pattern 进行正则校验 -->
      <van-field
        v-model="form.userName"
        name="pattern"
        placeholder="请输入用户名"
        :rules="[
          { pattern, message: '用户只能是3~10位字母或数字，不能有特殊符号' },
        ]"
      />
      <!-- 通过 validator 进行函数校验 -->
      <van-field
        v-model="form.password"
        name="validator"
        placeholder="请输入密码"
        :rules="[
          { validator, message: '密码只能是4~10位字母或数字，不能有特殊符号' },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          @click="onSubmit(form)"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        userName: "",
        password: "",
      },
      pattern: /[0-9a-zA-Z]{3,10}/,
    };
  },
  methods: {
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      return /[0-9a-zA-Z]{4,10}/.test(val);
    },
    onFailed(errorInfo) {
      console.log("failed", errorInfo);
    },
    onSubmit: function (formName) {
      //alert(formName.name+" "+formName.password);
      //this.$router.push("/main");
      //使用axios向后端发出登录请求
      this.$axios
        .post("login", formName)
        .then((res) => {
          console.log(res);
          localStorage.setItem("token", res.data.info);
          //sessionStorage.setItem("userName", res.data.info.loginName);
          //当请求成功后页面导航到后台主页main
          if (res.data.statusCode == 200) {
            // this.$toast.success('登录成功');
            const toast = this.$toast.loading({
              duration: 0, // 持续展示 toast
              forbidClick: true,
              message: "倒计时 3 秒",
            });

            let second = 3;
            const timer = setInterval(() => {
              second -= 0.5;
              if (second) {
                toast.message = `登陆中... ${second} 秒`;
              } else {
                clearInterval(timer);
                // 手动清除 Toast
                this.$toast.clear();
              }
            }, 400);
            this.$router.push({ path: "/", query: formName });
          } else {
            this.$toast.success("登录成功");
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    onClickLeft:function(){
      this.$router.go(-1)
    }
  },
};
</script>